/**
 * Created by xinhuang on 15/3/9.
 */
(function () {
  'use strict';
  angular.module('directives.timeValidate', [])
    /*
     *  表单验证（开始结束时间比对）
     *  endTime 加在开始时间的input上，
     *  startTime 加在结束时间的input上
     **/
    .directive('timeValidate', timeValidate)
    .directive('timeQuart', timeQuart)
    .directive('maxDate', maxDate)
    .directive('timeDate',timeDate);

  function timeValidate() {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        timeValidate: '@',
        endTime: '=',
        startTime: '='
      },
      link: postLink
    };

    function postLink(scope, ele, attr, ctrl) {
			ele[0].onmousewheel = function(){
				return false;
			};
      //判断是开始时间还是结束时间
      var time = scope.endTime ? 'endTime' : 'startTime';
      //监控对应的开始时间（结束时间）变化，并清除错误样式
      scope.$watch(time, function (n, o) {
        if (n === o) {
          return;
        }
        ctrl.$setUntouched();
        // ctrl.$setValidity('month', true);
        ctrl.$setValidity('time-error', true);
        ctrl.$setValidity('time-great', true);
      }, true);
      //当改变ngModel的值时，应做出判断并给予样式警告
      ctrl.$parsers.unshift(function (viewValue) {
        var required;
        if(is.string(viewValue)){
          required = viewValue.substring(0,4);
        }
        if(!viewValue || Number(required) <= 1999){
          ctrl.$setValidity('date', false);
        }else {
          ctrl.$setValidity('date', true);
          //当前选择的时间
          var modelTime = getTime(viewValue);
          //当前选择的时间对应的时间;如当前修改的是开始时间，那么scope[time]就是结束时间
          var scopeTime = getTime(scope[time]);
          var now = getTime(new Date());
          var isEndTime = time === 'endTime';
          if (isEndTime) {
            //当修改的是开始时间 并且结束时间是正常日期
            if(scopeTime){
              ctrl.$setValidity('time-error', modelTime <= scopeTime);
            }
          } else {
            //当修改的是结束时间 并且开始时间是正常日期
            if(scopeTime){
              ctrl.$setValidity('time-error', scopeTime <= modelTime);
            }
            ctrl.$setValidity('too-great', modelTime <= now);
          }
          return viewValue;
        }
      });

      function getTime(date) {
        var isDate = is.date(date);
        //当年的第一天：例2015年1月1号
        var year,week;
        switch (scope.timeValidate) {
          case 'year':
            return isDate ? date.getFullYear() : Number(date);
          case 'month':
          case 'day':
            return (new Date(date)).setHours(0);
          case 'week':
            if(isDate){
              year = date.getFullYear();
              week = getWeek(date) * Number(year);
            }else {
             week = date.substring(6,8) * Number(date.substring(0,4));   
            }
            return week;
          case 'hours':
            if (typeof date === 'string') {
              date = date.replace('T', ' ');
            }
            return new Date(date).setMinutes(0);
        }
      }
      function getWeek(date) {
       var date2=new Date(date.getFullYear(), 0, 1);
       //今天的礼拜几
       var day1=date.getDay();  
       if(day1===0){
        day1=7;
       }
       //今年的1月1号是礼拜几
       var day2=date2.getDay();  
       if(day2===0){
        day2=7;
       }  
       var d = Math.round((date.getTime() - date2.getTime()+(day2-day1)*(24*60*60*1000)) / 86400000);    
       return Math.ceil(d /7)+1;   
      }
    }
  }

// 季度指令
  /*
   *  季度验证（在HTML标签上加属性time-quart="quart"）
   *  startQuarter   endQuarter   年份input内添加属性：
   *  endTime     加在开始时间的input上，(年份开始时间)
   *  startTime   加在结束时间的input上，(年份结束时间)
   *
   *  startYear      endYear      在季度的select内添加属性：
   *  endQuarter     在开始季度的select内添加：
   *  startQuarter   在结束季度的select内添加：
   **/
  function timeQuart() {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        timeQuart: '@',
        endTime: '=',
        startTime: '=',
        startYear: '=',
        endYear: '=',
        endQuarter: '=',
        startQuarter: '='
      },
      link: postLink
    };
    function postLink(scope, ele, attr, ctrl) {
      var time = scope.endTime || scope.startTime ? (scope.endTime ? 'endTime' : 'startTime') : (scope.endQuarter ? 'endQuarter' : 'startQuarter');
      scope.$watch(time, function (n, o) {
        // if (n === o) return;
        ctrl.$setUntouched();
        ctrl.$setValidity('time-error', true);
        ctrl.$setValidity('quarter-error', true);
        ctrl.$setValidity('too-great', true);
      }, true);
      //当改变ngModel的值时，应做出判断并给予样式警告
      ctrl.$parsers.unshift(function (viewValue) {
        //传进来的时间(ng-model)
        var middleTime = getTime(viewValue);
        //DOM中设置的时间(start,end)
        var scopeTime = getTime(scope[time]);
        var now = getTime(new Date());
        // 现在季度
        var nowQ = getQuarter();
        var isEndTime = (time === 'endTime' || time === 'endQuarter');
        if (isEndTime) {
          if (time === 'endQuarter') {
            ctrl.$setValidity('too-great', middleTime - 0 + scope.startYear * 4 <= nowQ - 0 + now * 4);
            ctrl.$setValidity('quarter-error', middleTime - 0 + scope.startYear * 4 <= scopeTime - 0 + scope.endYear * 4);
          } else {
            //超过当前时间了
            ctrl.$setValidity('too-great', scope.startQuarter - 0 + middleTime * 4 <= nowQ - 0 + now * 4);
            //开始年份超过结束年份了
            ctrl.$setValidity('time-error', middleTime <= scopeTime);
            //开始时间超过结束时间了
            ctrl.$setValidity('quarter-error', scope.startQuarter - 0 + middleTime * 4 <= scope.endQuarter - 0 + scopeTime * 4);
          }
        } else {
          if (time === 'startQuarter') {
            ctrl.$setValidity('too-great', middleTime - 0 + scope.endYear * 4 <= nowQ - 0 + now * 4);
            ctrl.$setValidity('quarter-error', scopeTime - 0 + scope.startYear * 4 <= middleTime - 0 + scope.endYear * 4);
          } else {
            ctrl.$setValidity('too-great', scope.endQuarter - 0 + middleTime * 4 <= nowQ - 0 + now * 4);
            ctrl.$setValidity('time-error', scopeTime <= middleTime);
            ctrl.$setValidity('quarter-error', scope.startQuarter - 0 + scopeTime * 4 <= scope.endQuarter - 0 + middleTime * 4);
          }
        }
        return viewValue;
      });

      function getTime(date) {
        var isDate = is.date(date);
        switch (scope.timeQuart) {
          case 'year':
            return isDate ? date.getFullYear() : Number(date);
          case 'quart':
            if (scope.endTime || scope.startTime) {
              return isDate ? date.getFullYear() : Number(date);
            } else {
              return isDate ? date.getFullYear() : (is.object(date) ? date.code : date);
            }
          case 'month':
          case 'day':
            return (new Date(date)).setHours(0);
          case 'hours':
            if (typeof date === 'string') {
              date = date.replace('T', ' ');
            }
            return new Date(date).setMinutes(0);
        }
      }

      function getQuarter() {
        var getMon = new Date().getMonth() + 1;
        return Math.ceil(getMon / 3);
      }
    }
  }

// 时间不允许超过当前时间指令

  function maxDate() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: postLink
    };

    function postLink(scope, ele, attr, ctrl) {
      ctrl.$parsers.unshift(function (viewValue) {
        var now = (new Date(new Date())).setHours(0);
        var modelTime = (new Date(viewValue)).setHours(0);
          ctrl.$setValidity('cuo-great',  modelTime >= now);
        return viewValue;
      });

    }
  }

  function timeDate(){
    return {
      restrict: 'A',
      require: 'ngModel',
      link: postLink
    };
    function postLink(scope, ele, attr, ctrl) {
			ele[0].onmousewheel = function(){
				return false;
			};
      ctrl.$parsers.unshift(function (viewValue) {
        if(!viewValue){
          ctrl.$setValidity('date', false);
        }else {
          var year = new Date(viewValue).getFullYear();
          if(year <= 1999){
            ctrl.$setValidity('date', false);
          }else {
            var now = (new Date(new Date())).setHours(0);
            var modelTime = (new Date(viewValue)).setHours(0);
            ctrl.$setValidity('too-great',  modelTime <= now);
            return viewValue;
          }
        }
      });

    }
  }
})();